package cn.team.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.team.entity.User;
import cn.team.service.UserService;
import org.springframework.http.MediaType;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;

import cn.team.enums.FilePath;
@RequestMapping("/file")
@RestController("file")
public class FileController {
    @Resource
    UserService userService;
    @GetMapping("/getFile")
    public void getFile() {
    }

    @GetMapping("/getPortrait/{username}")
    public void getPortrait(HttpServletRequest request,
                            HttpServletResponse response, @PathVariable("username")String username
                            ) {
        User user = userService.getUser(username);
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
        File file = new File(FilePath.PORTRAIT_FILE_PATH.getName()+user.getPortraitName());
        if (file.exists()) {
            try (ServletOutputStream os = response.getOutputStream();
                FileInputStream fis = new FileInputStream(file)
            ) {
                FileCopyUtils.copy(fis, os);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    public static String getDefaultPortrait() {
        String[] names =new String[]{"pt1","pt2","pt3","pt4","pt5","pt6","pt7","pt8"};
        Random random = new Random();
        int i = random.nextInt(0,8);
        System.out.println(i+names[i]);
        return names[i]+".png";
    }
}
